package com.ayoka.parenting.ui.live.liveclassroom;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;

import com.ayoka.parenting.Constants;
import com.ayoka.parenting.R;
import com.ayoka.parenting.bean.BasicUserInfoBean;
import com.ayoka.parenting.bean.CustomMessageBean;
import com.ayoka.parenting.bean.DiscussGroupTempRoomBean;
import com.ayoka.parenting.bean.GrownClassroomDetailBean;
import com.ayoka.parenting.bean.UserInfoBean;
import com.ayoka.parenting.bean.UserManager;
import com.ayoka.parenting.databinding.ActivityLiveClassroomBinding;
import com.ayoka.parenting.mvp.MVPBaseActivity;
import com.ayoka.parenting.ui.live.ChatDialog;
import com.ayoka.parenting.ui.live.WhiteBoardDialog;
import com.ayoka.parenting.ui.live.discussgroup.DiscussGroupActivity;
import com.ayoka.parenting.ui.live.memberlist.MemberListActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jincp.common.dialog.DialogHelper;
import com.jincp.common.permission.MPermission;
import com.jincp.common.permission.annotation.OnMPermissionDenied;
import com.jincp.common.permission.annotation.OnMPermissionGranted;
import com.jincp.common.permission.annotation.OnMPermissionNeverAskAgain;
import com.jincp.common.utils.LiveDataBus;
import com.jincp.common.utils.MyLogger;
import com.jincp.common.utils.SharedPreferenceUtil;
import com.jincp.image.load.ImageLoader;
import com.jincp.image.load.ImageLoaderOptions;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMMessage;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.teduboard.TEduBoardController;
import com.tencent.ticsdk.core.TICManager;
import com.tencent.trtc.TRTCCloudDef;

import android.databinding.ViewDataBinding;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: LiveClassroomActivity.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class LiveClassroomActivity extends MVPBaseActivity<ActivityLiveClassroomBinding, LiveClassroomContract.View, LiveClassroomPresenter> implements
        LiveClassroomContract.View,
        TICManager.TICMessageListener,
        TICManager.TICEventListener,
        TICManager.TICIMStatusListener {

    private String[] permissionList = {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, LiveClassroomActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        activity.startActivity(intent);
    }

    private int roomId;
    private String scheduleId;

    private GrownClassroomDetailBean grownClassroomDetailBean;
    private int currentStep;

    private DiscussGroupTempRoomBean discussGroupTempRoomBean;

    private boolean historyDataSyncCompleted;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initData(null);
    }

    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
        //应用运行时，保持屏幕高亮，不锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    @Override
    protected int getContentLayout() {
        return R.layout.activity_live_classroom;
    }

    @Override
    protected void initViews() {
        mDataBinding.ivShutDown.setColorFilter(Color.WHITE);
        mDataBinding.tvCourseName.getCompoundDrawables()[2].setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
        mDataBinding.tvClassroomMemberCount.getCompoundDrawables()[0].setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
        mDataBinding.ivWhiteBoard.setColorFilter(Color.WHITE);
        mDataBinding.ivMessage.setColorFilter(Color.WHITE);

        mDataBinding.ivShutDown.setOnClickListener(this);
        mDataBinding.tvCourseName.setOnClickListener(this);
        mDataBinding.tvClassroomMemberCount.setOnClickListener(this);
        mDataBinding.layoutWhiteBoard.setOnClickListener(this);
        mDataBinding.layoutMessage.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        roomId = SharedPreferenceUtil.getInt("RoomId", 0);
        scheduleId = SharedPreferenceUtil.getString("ScheduleId", "");
        if (mPresenter != null) {
            mPresenter.enterLiveRoom(scheduleId);
            if (UserManager.getInstance().detailBean != null &&
                    UserManager.getInstance().detailBean.user_info != null &&
                    UserManager.getInstance().detailBean.user_info.BasicInfo != null) {
                mPresenter.saveMember(UserManager.getInstance().detailBean.user_info.BasicInfo);
            }
        }
    }

    @Override
    protected LiveClassroomPresenter getPresenter() {
        return new LiveClassroomPresenter();
    }

    @Override
    public void onClick(View view) {
        if (view == mDataBinding.ivShutDown) {
            onBackPressed();
        } else if (view == mDataBinding.tvCourseName) {
            if (mPresenter != null) {
                mDataBinding.tvClassroomMemberCount.setVisibility(View.INVISIBLE);
                mDataBinding.layoutCurrentStage.setVisibility(View.INVISIBLE);
                mPresenter.showCourseStepPopup(this, view, grownClassroomDetailBean.CourseTitle, currentStep);
            }
        } else if (view == mDataBinding.tvClassroomMemberCount) {
            MemberListActivity.start(this, false, mPresenter.getMemberList());
        } else if (view == mDataBinding.layoutWhiteBoard) {
            if (!historyDataSyncCompleted) { //
                showToast("请在历史数据同步完成后开始测试");
                return;
            }
            if (mPresenter != null) {
                mPresenter.showWhiteBoardDialog(getSupportFragmentManager());
                mDataBinding.layoutWhiteBoard.setEnabled(false);
            }
        } else if (view == mDataBinding.layoutMessage) {
            mDataBinding.viewMessage.setVisibility(View.GONE);
            if (mPresenter != null) {
                mPresenter.showChatMessageDialog(getSupportFragmentManager());
                mDataBinding.layoutMessage.setEnabled(false);
            }
        }
    }

    @Override
    public void configLiveRoomDetailData(GrownClassroomDetailBean data) {
        if (data == null) {
            finishDelay();
            return;
        }
        this.grownClassroomDetailBean = data;
        this.currentStep = grownClassroomDetailBean.CurrentStep;
        changeCourseStep();
        if (mPresenter != null && (currentStep != 2 && currentStep != 5)) {
            mPresenter.joinLiveRoom(roomId, TRTCCloudDef.TRTCRoleAudience);
        }
        mDataBinding.tvCourseName.setText(grownClassroomDetailBean.CourseTitle);
        mDataBinding.tvClassroomMemberCount.setText(String.valueOf(grownClassroomDetailBean.OnlineMemberCount));
        List<String> courseStepList = mPresenter.getCourseStepList();
        mDataBinding.tvCourseStepName.setText(courseStepList.get(currentStep));
        if (grownClassroomDetailBean.ClassRoom != null) {
            if (grownClassroomDetailBean.ClassRoom.Coach != null) {
                mPresenter.saveMember(grownClassroomDetailBean.ClassRoom.Coach);
                ImageLoader.getInstance().displayImage(grownClassroomDetailBean.ClassRoom.Coach.LocalAvatar, mDataBinding.ivCoachHeader);
                ImageLoader.getInstance().displayImage(grownClassroomDetailBean.ClassRoom.Coach.LocalAvatar, mDataBinding.ivCoachPortrait, ImageLoaderOptions.getCircleOptions());
                mDataBinding.tvCoachName.setText(grownClassroomDetailBean.ClassRoom.Coach.WeixinNickName);
            }
            mDataBinding.tvClassroomName.setText(grownClassroomDetailBean.ClassRoom.Title);
        }
    }

    /**
     * 添加白板
     */
    @Override
    public void addBoardView() {
        MyLogger.d(TAG, "正在使用白板：" + TEduBoardController.getVersion());
    }

    /**
     * 移出白板
     */
    private void removeBoardView() {
        MyLogger.d(TAG, "移出白板");
    }

    @Override
    public void onTEBHistoryDataSyncCompleted() {
        historyDataSyncCompleted = true;
        MyLogger.d(TAG, "历史数据同步完成");
    }

    /**
     * 加入房间回调
     */
    @Override
    public void onJoinLiveRoomCallback(boolean isSuccess) {
        if (isSuccess) {
            mDataBinding.trcVideoView.onRoomEnter();
            // 检查权限
            checkCameraAndMicPermission();
        } else {
            showToast("创建房间失败！即将推出房间");
            finishDelay();
        }
    }

    @Override
    public void configScheduleTempSubRoom(DiscussGroupTempRoomBean data) {
        if (data == null) {
            if (mPresenter != null) {
                mPresenter.joinLiveRoom(roomId, TRTCCloudDef.TRTCRoleAudience);
            }
        } else {
            this.discussGroupTempRoomBean = data;
            List<String> courseStepList = mPresenter.getCourseStepList();
            String step = courseStepList.get(currentStep);
            DialogHelper.getOkDialog(this, "提示", "当前为" + step + "， 需要进入讨论组", false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    mPresenter.quitLiveRoom(false, discussGroupTempRoomBean.subRoom);
                }
            }).show();
        }
    }

    @Override
    public void configOnlineMemberList(List<BasicUserInfoBean> memberList) {
        LiveDataBus.getInstance().with("MemberList", String.class).postValue("Notify");
        mDataBinding.tvClassroomMemberCount.setText(String.valueOf(memberList.size()));
    }

    /**
     * 退出房间回调
     */
    @Override
    public void onQuitLiveRoomCallback(boolean isSuccess, boolean needFinishActivity) {
        TICManager.getInstance().removeIMMessageListener(this);
        TICManager.getInstance().removeEventListener(this);
        TICManager.getInstance().removeIMStatusListener(this);
        removeBoardView();

        if (needFinishActivity) {
            finishDelay();
        }
    }

    @Override
    public void createDiscussGroupRoomCallback(boolean isSuccess, int roomId, String scheduleId) {
        if (isSuccess) {
            DiscussGroupActivity.start(this, roomId, scheduleId);
        }
    }

    @Override
    public void onDialogDismiss(DialogFragment dialog) {
        if (dialog instanceof WhiteBoardDialog) {
            mDataBinding.layoutWhiteBoard.setEnabled(true);
        } else if (dialog instanceof ChatDialog) {
            mDataBinding.layoutMessage.setEnabled(true);
        }
    }

    @Override
    public void onPopupDismiss(PopupWindow popupWindow) {
        mDataBinding.tvClassroomMemberCount.setVisibility(View.VISIBLE);
        mDataBinding.layoutCurrentStage.setVisibility(View.VISIBLE);
    }

    /**
     * 检测权限
     */
    private void checkCameraAndMicPermission() {
        if (MPermission.hasPermissions(this, permissionList)) {
            initTRTCloud();
        } else {
            MPermission.with(this).permissions(permissionList).setRequestCode(Constants.BASIC_PERMISSION_REQUEST_CODE).request();
        }
    }

    @OnMPermissionGranted(Constants.BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        initTRTCloud();
    }


    @OnMPermissionDenied(Constants.BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(Constants.BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionDenied() {
        showToast("授权失败");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 初始化腾讯直播
     */
    private void initTRTCloud() {
        TICManager.getInstance().addIMMessageListener(this);
        TICManager.getInstance().addEventListener(this);
        TICManager.getInstance().addIMStatusListener(this);
    }


    private void changeCourseStep() {
        List<String> courseStepList = mPresenter.getCourseStepList();
        mDataBinding.tvCourseStepName.setText(courseStepList.get(currentStep));
        // 不进入讨论组
//        if (currentStep == 2 || currentStep == 5) {
//            if (mPresenter != null) {
//                mPresenter.getScheduleTempSubRoom(scheduleId);
//            }
//        }
    }

    @Override
    public void onTICReceiveTextMessage(String userId, String content, TIMMessage message) {
        if (mPresenter != null) {
            mPresenter.saveChatMessage(userId, true, content, "Receive", message);
        }
        if (mDataBinding.viewMessage.getVisibility() == View.GONE) {
            mDataBinding.viewMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTICReceiveCustomMessage(String fromUserId, byte[] data) {
        MyLogger.d(TAG, "onTICReceiveGroupCustomMessage");
    }

    @Override
    public void onTICReceiveGroupTextMessage(String fromUserId, String text, TIMMessage message) {
        if (mPresenter != null) {
            mPresenter.saveChatMessage(fromUserId, false, text, "Receive", message);
        }
        if (mDataBinding.viewMessage.getVisibility() == View.GONE) {
            mDataBinding.viewMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTICReceiveGroupCustomMessage(String fromUserId, byte[] data) {
        MyLogger.d(TAG, "onTICReceiveGroupCustomMessage");
        try {
            Gson gson = new GsonBuilder().create();
            CustomMessageBean customMessage = gson.fromJson(new String(data), CustomMessageBean.class);
            if (TextUtils.equals(customMessage.command, "change_step")) {
                currentStep = Integer.valueOf(customMessage.value);
                changeCourseStep();
            } else if (TextUtils.equals(customMessage.command, "course_completed")) {
                showToast("即将结束本次课程！");
                LiveDataBus.getInstance().with("CreateCourse", Boolean.class).postValue(true);
                mPresenter.quitLiveRoom(false, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTICReceiveMessage(TIMMessage message) {
        MyLogger.d(TAG, "onTICReceiveMessage");
    }

    @Override
    public void onTICForceOffline() {
        showToast("您已被踢下线，请检查后重新登录");
        finishDelay();
    }

    @Override
    public void onTICUserSigExpired() {
        showToast("用户签名已过期！");
        finishDelay();
    }

    @Override
    public void onTICUserVideoAvailable(String userId, boolean available) {
        if (available) {
            final TXCloudVideoView renderView = mDataBinding.trcVideoView.onMemberEnter(userId);
            if (renderView != null) {
                renderView.setUserId(userId);
                // 启动远程画面的解码和显示逻辑，FillMode 可以设置是否显示黑边
                TICManager.getInstance().getTRTCCloud().setRemoteViewFillMode(userId, TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FIT);
                TICManager.getInstance().getTRTCCloud().startRemoteView(userId, renderView);
            }
        } else {
            TICManager.getInstance().getTRTCCloud().stopRemoteView(userId);
            mDataBinding.trcVideoView.onMemberLeave(userId);
        }
        mDataBinding.ivCoachHeader.setVisibility(available ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onTICUserSubStreamAvailable(String userId, boolean available) {
        if (available) {
            final TXCloudVideoView renderView = mDataBinding.trcVideoView.onMemberEnter(userId);
            if (renderView != null) {
                renderView.setUserId(userId + TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SUB);
                TICManager.getInstance().getTRTCCloud().setRemoteViewFillMode(userId, TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FIT);
                TICManager.getInstance().getTRTCCloud().startRemoteSubStreamView(userId, renderView);
            }
        } else {
            TICManager.getInstance().getTRTCCloud().stopRemoteSubStreamView(userId);
            mDataBinding.trcVideoView.onMemberLeave(userId);
        }
    }

    @Override
    public void onTICUserAudioAvailable(String userId, boolean available) {
        if (available) {
            final TXCloudVideoView renderView = mDataBinding.trcVideoView.onMemberEnter(userId);
            if (renderView != null) {
                renderView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onTICMemberJoin(List<String> userList) {
        MyLogger.d(TAG, "onTICMemberJoin" + userList.toString());
        if (mPresenter != null && !userList.isEmpty()) {
            mPresenter.setMemberJoin(userList);
        }
    }

    @Override
    public void onTICMemberQuit(List<String> userList) {
        MyLogger.d(TAG, "onTICMemberQuit" + userList.toString());
        if (mPresenter != null && !userList.isEmpty()) {
            mPresenter.setMemberQuit(userList);
        }
    }

    @Override
    public void onTICVideoDisconnect(int errCode, String errMsg) {

    }

    @Override
    public void onTICClassroomDestroy() {
        showToast("课堂已销毁");
        finishDelay();
    }

    @Override
    public void onTICSendOfflineRecordInfo(int code, String desc) {
        MyLogger.d(TAG, "同步录制信息， code = " + code);
    }

    @Override
    public void onUserVoiceVolume(ArrayList<TRTCCloudDef.TRTCVolumeInfo> userVolumes, int totalVolume) {
        mDataBinding.trcVideoView.resetAudioVolume();
        for (int i = 0; i < userVolumes.size(); i++) {
            MyLogger.d(TAG, "" + userVolumes.get(i).volume);
            mDataBinding.trcVideoView.updateAudioVolume(userVolumes.get(i).userId, userVolumes.get(i).volume);
        }
    }

    @Override
    public void onFirstVideoFrame(String userId, int streamType, int width, int height) {
    }

    @Override
    public void onSendFirstLocalVideoFrame(int streamType) {
    }

    @Override
    public void onNetworkQuality(TRTCCloudDef.TRTCQuality localQuality, ArrayList<TRTCCloudDef.TRTCQuality> remoteQuality) {
        mDataBinding.trcVideoView.updateNetworkQuality(localQuality.userId, localQuality.quality);
        if (localQuality.quality > 5) {
            showToast("当前你的网络信号差");
        }
        for (TRTCCloudDef.TRTCQuality qualityInfo : remoteQuality) {
            mDataBinding.trcVideoView.updateNetworkQuality(qualityInfo.userId, qualityInfo.quality);
            if (qualityInfo.quality > 5) {
                showToast("当前对方的网络信号差");
            }
        }
    }

    @Override
    public void onCapturedAudioFrame(TRTCCloudDef.TRTCAudioFrame trtcAudioFrame) {

    }

    @Override
    public void onBackPressed() {
        if (mPresenter != null) {
            mPresenter.showExitDialog(this);
        } else {
            finish();
        }
    }
}
